package cn.liuweiwei.handler;

import cn.liuweiwei.util.JWTUtils;
import cn.liuweiwei.util.Result;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;


@Component
public class ResourceInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (request.getMethod().equalsIgnoreCase("GET")) {
            return true;
        }
        String token = request.getHeader("token");
        if (Objects.isNull(token)) {
            writeJsonObj(response, "抱歉、你未认证，请先认证");
            return false;
        }
        try {
            JWTUtils.verify(token);
            return true;
        } catch (Exception ex) {
            writeJsonObj(response, ex.getMessage());
            return false;
        }
    }

    private void writeJsonObj(HttpServletResponse response, String message) throws IOException {
        String jsonObj = new ObjectMapper()
                .writeValueAsString(Result.error(message));
        response.setContentType("application/json; charset=utf8");
        response.getWriter().write(jsonObj);
    }

}
